package com.mmdccj.yugu.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.util.Enumeration;

/***
 * @Author: MMDCCJ
 * @date: 2023-11-26 02:16
 *
 * 登录过滤器
 */
@Slf4j
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        /**
         * 解决前端跨域与编码报错问题
         */
        String curOrigin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setContentType("text/text;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        // 获取请求地址
        String requestURI = request.getRequestURI();
        log.info("请求地址{}", requestURI);
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println("Cookie Name: " + cookie.getName());
                System.out.println("Cookie Value: " + cookie.getValue());
                // 可以打印其他 cookie 属性，比如路径、域名、有效期等等，根据需要打印相关信息
                // System.out.println("Cookie Path: " + cookie.getPath());
                // System.out.println("Cookie Domain: " + cookie.getDomain());
                // ...
            }
            HttpSession session = request.getSession();
            Enumeration<String> attributeNames = session.getAttributeNames();

            while (attributeNames.hasMoreElements()) {
                String attributeName = attributeNames.nextElement();
                Object attributeValue = session.getAttribute(attributeName);
                System.out.println("Attribute Name: " + attributeName);
                System.out.println("Attribute Value: " + attributeValue);
            }
        }
        log.info("session->{}", request.getSession().getAttribute("user"));
        // 无需过滤的请求
        String[] urls = new String[]{
                "/user/login/*",
                "/user/register/**",
                "/user/getSingerInfo",
                "/user/getPublicInfo",
                "/user/socialInfo",
                "/user/getCollectUsers",
                "/user/getMyMusicList",
                "/common/*",
                "/musicList/*",
                "/music/*",
                "/singerInfo/**",
                "/follow/follows",
                "/follow/fans",
                "/search/**",
                "/comment/getComment",
                "/static/**",
                "/post/getMyPost",
                "/web/**",
                "/comment/sendComment"
        };
        if (check(urls, requestURI)) {
            log.info("不需要处理的请求{}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }

        log.info("未登录");
        response.getWriter().write("NOT-LOGIN");
    }

    /**
     * 匹配无需过滤的请求
     *
     * @param urls       url总表
     * @param requestURI 请求url
     * @return boolean
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) return true;
        }
        return false;
    }
}
